<?php
namespace app\api\controller;

use app\admin\model\Construction;
use app\admin\model\Type;
use app\common\controller\Api;
use think\Exception;
use think\Request;
use app\api\library\Map as MapService;

class Map extends Api {

    //该类的方法不需要登录
    protected $noNeedLogin = ['*'];


    public function __construct(Request $request = null)
    {
        parent::__construct($request);
    }


    /**
     * 获取类型接口
     */
    public function getTypeList()
    {
        $typeModel = new Type();
        $type_list = $typeModel->field('id,nickname,avatar')->order('weight desc')->select();

        $this->success('成功',$type_list);
    }


    /**
     * 获取construction信息
     * get
     * params type_id
     * params region_name
     * @return void
     */
    public function getConstructionList(){
        //参数验证
        $type_id = $this->request->get('type_id');
        $region_name = $this->request->get('region_name');
        $industry_id =  $this->request->get('industry_id');
        $name = $this->request->get('name');
        if(empty($region_name)||(empty($type_id)&&$type_id!=0)){
            $this->error('参数错误');
        }
        //构建查询条件
        $constructionModel = new Construction();
        $where = [
            'region_name' => $region_name, //区域名称
            'type_id' =>$type_id //类型id
        ];
        if($type_id==0)unset($where['type_id']);
        if($region_name=='all')unset($where['region_name']);
        if(!empty($industry_id)){
            $industry_ids = \app\admin\controller\Industry::getChildren($industry_id);
            array_push($industry_ids,$industry_id);
            $where['industry_id'] = ['in',$industry_ids];
        }
        if(!empty($name)){
            $where['nickname'] = ['LIKE',"%$name%"];
        }
        //数据查询及错误捕获
        try {
            $data = $constructionModel->where($where)->select();
            //$data = db('construction')->where($where)->select();
            foreach ($data as &$value){
                //将mark点坐标转换
                if(!empty($value['lat'])&&!empty($value['lng'])){
                    $mark_arr = [
                        'lng'=>$value['lng'],
                        'lat'=>$value['lat']
                    ];

                    $new_mark_arr = $this->convert($mark_arr);
                    if(isset($new_mark_arr['lng'])){
                        $value['lng'] = $new_mark_arr['lng'];
                        $value['lat'] = $new_mark_arr['lat'];
                    }
                }
                $coordinate_region_str = $value->coordinate_region;
                $coordinate_region_arr = $this->coordinate_region($coordinate_region_str);
                $value->coordinate_region = $coordinate_region_arr;
            }
            $this->success('成功',$data);
        }catch (Exception $e){
            $this->error('获取失败，错误信息：'.$e->getMessage(),$e->getData());
        }
    }


    public function get_region(){
        $data = db('region')->field('id,nickname,latitude,longitude,coordinate')->select();
        //return json($data);
        foreach ($data as &$value){
            if(!empty($value['coordinate'])){
                $value['coordinate'] = $this->coordinate_region($value['coordinate']);
            }
        }
        $this->success('成功',$data);
    }

    /**
     * coordinate_region 类型调整
     */
    protected function coordinate_region($coordinate_region_str){
        if(empty($coordinate_region_str)||trim($coordinate_region_str) === ''){
            return [];
        }
        //去掉最外面的[]
        //$length = strlen($coordinate_region_str);
        //$coordinate_region_str = substr($coordinate_region_str, 1, $length - 2);
        //替换''为"" 后使用json_decode转换为数组
        //$jsonStr = str_replace("'", '"', $coordinate_region_str);

        $array = json_decode($coordinate_region_str, true);


        //坐标转换
        foreach($array as &$arr){
            $new_arr = [
                'lng'=>$arr[1],
                'lat'=>$arr[0]
            ];
            $res_arr = $this->convert($new_arr);
            $arr[1] = $res_arr['lng'];
            $arr[0] = $res_arr['lat'];
        }
        //将数组第一个经纬度复制一份到最后
        array_push($array,$array[0]);

        //将每个经纬度设置成数组
        /*foreach ($array as &$v){
            $v = array_map(function($element) {
                return [$element];
            }, $v);
        }*/



        return $array;
    }

    public function convert($arr){
        $mapservice = new MapService();

        $new_arr = $mapservice->wgs84togcj02($arr['lng'],$arr['lat']);
        return $new_arr;

        //该方式转换有次数限制
        // if(empty($arr)){
        //     return [];
        // }
        // $str = implode(',',$arr);
        // $data = [
        //     'key'=>'OXIBZ-XS2LZ-4C3X7-7XLEJ-4QKSF-KLFDQ',
        //     //'locations'=>'30.417369523645117,114.37409162521364',
        //     'locations'=>$str,
        //     'type'=>1
        // ];
        // $res = sendGET('https://apis.map.qq.com/ws/coord/v1/translate',$data);
        // dump($res);
        // if(empty($res)||(!isset($res['status'])&&$res['status']!=0)){
        //     $this->error('坐标转换出错');
        // }
        // if(isset($res['locations'])){
        //     return $res['locations'];
        // }
        // $this->error('坐标转换出错');


    }

    // public function miaoshan(){
    //     $mapservice = new MapService();
    //     $data = db('region')->where('id',4)->value('coordinate');
    //     $array = json_decode($data, true);
    //     foreach($array as &$arr){
    //         $new_arr = [
    //             'lng'=>$arr[1],
    //             'lat'=>$arr[0]
    //         ];
    //         $res_arr = $mapservice->gcj02towgs84($new_arr['lng'],$new_arr['lat']);

    //         $arr[1] = $res_arr[0];
    //         $arr[0] = $res_arr[1];
    //     }
    //     $str = json_encode($array,true);
    //     try {
    //         db('region')->where('id',4)->update(['coordinate'=>$str]);
    //         $this->success('chenggong');
    //     }catch (Exception $e){
    //         $this->error($e->getMessage());
    //     }
    // }
}
